﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace TheLocal.Core
{
    public class Downloader : IDisposable
    {
        private bool disposed;
        private HttpWebRequest request;
        private Action<string> completedRequestAction;
        private bool downloadComplete;

        public Downloader()
        {
        }

        public Downloader(Action<string> completedRequestAction)
        {
            this.completedRequestAction = completedRequestAction;
        }

        public void Download(string uri)
        {
            this.Download(new Uri(uri));
        }

        public void Download(Uri uri)
        {
            this.request = HttpWebRequest.CreateHttp(uri);
            this.request.BeginGetResponse(new AsyncCallback(GetResponseStream), request);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public bool DownloadComplete
        {
            get 
            { 
                return downloadComplete; 
            }
            private set 
            {
                if (downloadComplete != value)
                {
                    downloadComplete = value;
                }
            }
        }

        private void GetResponseStream(IAsyncResult ar)
        {
            var resultRequest = ar.AsyncState as HttpWebRequest;
            string responseString = string.Empty;

            try
            {
                WebResponse streamResponse = resultRequest.EndGetResponse(ar);
                StreamReader streamRead = new StreamReader(streamResponse.GetResponseStream());
                responseString = streamRead.ReadToEnd();
            }
            catch (WebException webException)
            {
                Debug.WriteLine("Request got cancelled before completion : {0}", webException.Message);
            }
            finally
            {
                this.downloadComplete = true;

                if (this.completedRequestAction != null)
                {
                    this.completedRequestAction(responseString);
                }
            }
        }

        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (this.request != null)
                    {
                        this.request.Abort();
                        this.completedRequestAction = null;
                    }
                }
            }
            this.disposed = true;
        }
    }
}
